package me.jiatao.baselibrary.ui.activity

import android.app.Activity
import android.content.Context
import android.graphics.PixelFormat
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.classic.common.MultipleStatusView
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity
import me.jiatao.baselibrary.R
import me.jiatao.baselibrary.common.AppManager
import me.jiatao.baselibrary.event.NetworkChangeEvent
import me.jiatao.baselibrary.ext.onClick
import me.jiatao.baselibrary.utils.KeyBoardUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Activity基类，与业务无关
 */
abstract class BaseActivity : RxAppCompatActivity() {

    /**
     * 提示View
     */
    lateinit var mTipView: View
        private set

    private lateinit var mWindowManager: WindowManager
    private lateinit var mLayoutParams: WindowManager.LayoutParams
    /**
     * 多种状态的 View 的切换
     */
    protected var mLayoutStatusView: MultipleStatusView? = null

    /**
     * 是否使用 EventBus
     */
    open fun useEventBus(): Boolean = true

    /**
     * 是否需要显示显示网络提示对话框
     */
    open fun enableNetworkTip(): Boolean = true


    protected lateinit var mActivity: Activity

    override fun onCreate(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        super.onCreate(savedInstanceState)
        mActivity = this
        //加入到Activity管理中
        AppManager.instance.addActivity(this)

        initView()
        initEventBus()
    }

    /**
     * 处理输入法自动收起
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP) {
            val v = currentFocus
            // 如果不是落在EditText区域，则需要关闭输入法
            if (KeyBoardUtil.isHideKeyboard(v, ev)) {
                KeyBoardUtil.hideKeyBoard(this, v)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun finish() {
        if (mTipView.parent != null) {
            mWindowManager.removeView(mTipView)
        }
        AppManager.instance.finishActivity(this)
        super.finish()
    }

    override fun onDestroy() {
        if (useEventBus()) {
            EventBus.getDefault().unregister(this)
        }
        KeyBoardUtil.fixInputMethodManagerLeak(this)
        super.onDestroy()
    }


    /**
     * 初始化EventBus
     */
    private fun initEventBus() {
        if (useEventBus()) {
            EventBus.getDefault().register(this)
        }
    }

//region View
    /**
     * 初始化View
     */
    private fun initView() {
        initTipView()
        initLayoutStatusView()
    }

    /**
     * 初始化 TipView
     */
    private fun initTipView() {
        mTipView = layoutInflater.inflate(R.layout.layout_network_tip, null)
        mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mLayoutParams = WindowManager.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
            PixelFormat.TRANSLUCENT
        )
        mLayoutParams.gravity = Gravity.TOP
        mLayoutParams.x = 0
        mLayoutParams.y = 0
        mLayoutParams.windowAnimations = R.style.TopDownAnimation // add animations
    }

    /**
     * 初始化多状态视图
     */
    private fun initLayoutStatusView() {
        mLayoutStatusView?.setOnRetryClickListener {
            loadNetData()
        }
    }

    /**
     * 初始化toolbar
     */
    protected fun initToolbar(toolbar: Toolbar, homeAsUpEnabled: Boolean, title: String) {
        toolbar?.title = title
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(homeAsUpEnabled)
    }

//endregion

//region 网络监听

    /**
     * 网络连接后自动加载数据
     */
    open fun loadNetData() {}

    /**
     * 无网状态—>有网状态 的自动重连操作，子类可重写该方法
     */
    open fun doReConnected() {
        loadNetData()
    }

    /**
     * Network Change
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetworkChangeEvent(event: NetworkChangeEvent) {
        checkNetwork(event.isConnected)
    }

    private fun checkNetwork(isConnected: Boolean) {
        if (enableNetworkTip()) {
            if (isConnected) {
                doReConnected()
                if (mTipView != null && mTipView.parent != null) {
                    mWindowManager.removeView(mTipView)
                }
            } else {
                if (mTipView.parent == null) {
                    mWindowManager.addView(mTipView, mLayoutParams)
                }
            }
        }
    }
//endregion

    protected fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
}